package com.wn.sk.product.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2022 -11-11
 * @desc 队列 和 交换机的创建
 * 队列 和 交换机绑定
 */
@Configuration
public class RabbitConfig {

    //创建队列

    @Bean("normalQueue")
    public Queue normalQueue() {

        Map<String,Object> params = new HashMap<>();
        params.put("x-message-ttl", 20000);     //ttl
        params.put("x-dead-letter-exchange", "dead_order_exchange");  //绑定死信交换机
        params.put("x-dead-letter-routing-key", "order.dead.key");        //死信交换机和路由的绑定
        Queue normal_order_queue = new Queue("normal_order_queue",true,true,false,params);

        return normal_order_queue;
    }

    //创建交换机
    @Bean("normalDirectExchange")
    public DirectExchange normalDirectExchange() {
        return new DirectExchange("normal_order_exchange");
    }

    //绑定交换机
    @Bean("bindingNormalQueue")
    public Binding bindingNormalQueue(
            @Qualifier("normalQueue") Queue queue,
            @Qualifier("normalDirectExchange") DirectExchange exchange
    ) {
        return BindingBuilder.bind(queue).to(exchange).with("order.normal.key");
    }

    @Bean("deadQueue")
    public Queue deadQueue() {
        return new Queue("dead_order_queue");
    }

    //创建交换机
    @Bean("deadDirectExchange")
    public DirectExchange deadDirectExchange() {
        return new DirectExchange("dead_order_exchange");
    }

    //绑定交换机
    @Bean("bindingDeadQueue")
    public Binding bindingDeadQueue(
            @Qualifier("deadQueue") Queue queue,
            @Qualifier("deadDirectExchange") DirectExchange exchange
    ) {
        return BindingBuilder.bind(queue).to(exchange).with("order.dead.key");
    }

    // 如果 我们的 MQ中的 Exchange\Queue不会创建 加下面的代码
    @Bean
    public RabbitAdmin rabbitAdmin(
            ConnectionFactory factory,
            Exchange normalDirectExchange,
            Exchange deadDirectExchange,
            Queue normalQueue,
            Queue deadQueue) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.declareExchange(normalDirectExchange);
        rabbitAdmin.declareExchange(deadDirectExchange);
        rabbitAdmin.declareQueue(normalQueue);
        rabbitAdmin.declareQueue(deadQueue);
        return rabbitAdmin;
    }

}
